import random
import re

from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from djangoProject.settings import RONG_LIAN_YUN_CLASS
from home.models import UserModel, HealthInfoCategory, HealthCategory, SubCategory, HealthItem, Hospital, Department, \
    Doctor, UserQuestion, DoctorResponse, Medicine, DoctorHospitalMedicine, Video, Patient
from home.serializers import HealthInfoCategorySerializer, HealthCategorySerializer, HealthCategorySubSerializer, \
    HealthItemSerializer, HospitalSerializer, DepartmentSerializer, DoctorSerializer, UserQuestionSerializer, \
    DoctorResponseSerializer, MedicineSerializer, DoctorMedicineSerializer, VideoSerializer, UserSerializer, \
    PatientSerializer


# Create your views here.

# 测试创建用户
class CreateUserAPIView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        # 检查用户名是否已存在
        if UserModel.objects.filter(username=username).exists():
            return Response({'msg': '用户名已存在', 'code': 400})

        # 检查密码格式
        if not re.match(r'^[a-zA-Z0-9_-]{6,20}$', password):
            return Response({'msg': '密码格式不正确', 'code': 400})

        # 准备用户数据
        user_data = {
            'username': username,
            'password': password
        }

        if '@' in username and 'com' in username:
            user_data['email'] = username
            UserModel.objects.create_user(**user_data)
            return Response({'msg': '注册成功', 'code': 200})


        elif re.match(r'^1[3-9]\d{9}$', username):
            user_data['phone'] = username
            UserModel.objects.create_user(**user_data)
            return Response({'msg': '注册成功', 'code': 200})
        return Response({'msg': '请输入正确的手机号或邮箱', 'code': 400})


# 用户注册
class UserRegisterAPIView(CreateAPIView):
    queryset = UserModel.objects.all()
    serializer_class = UserQuestionSerializer


# 短信验证码
class SmsCodeAPIView(APIView):
    def get(self, request, phone):
        redis = get_redis_connection("sms_code")

        res_interval = redis.ttl(f"interval_{phone}")
        if res_interval > 0:
            return Response({'msg': '请勿频繁发送短信', 'code': 400})

        tid = RONG_LIAN_YUN_CLASS.get("tid")
        time = RONG_LIAN_YUN_CLASS.get("time")
        interval = RONG_LIAN_YUN_CLASS.get("interval")  # 验证码有效时间   单位：秒

        code = f"{random.randint(0, 9999):04d}"
        interval_time = interval // 60  # 验证码有效时间   单位：分钟
        content = (code, interval_time)
        from mycelery.sms.tasks import send_sms
        send_sms.delay(tid, phone, content)
        pipe = redis.pipeline()  # 开启管道
        pipe.multi()  # 开启事务
        redis.setex(f"sms_{phone}", time, code)  # time 单位：秒
        redis.setex(f"interval_{phone}", interval, '-')  # interval 单位：秒
        pipe.execute()  # 执行事务
        print(f"短信验证码已发送至{phone}, 验证码为{code}, 有效时间{interval_time}分钟")
        return Response({'msg': '短信验证码已发送', 'code': 200})


# 问医生9个分类
class HealthCategoryView(APIView):
    def get(self, request):
        health_info_category = HealthInfoCategory.objects.all()
        ser = HealthInfoCategorySerializer(health_info_category, many=True)
        return Response(ser.data)


# # # 大健康和生活手册
class HealthCategorySubView(APIView):
    def get(self, request):
        health_category = HealthCategory.objects.all()
        ser = HealthCategorySerializer(health_category, many=True)
        return Response(ser.data)


#   大健康和生活手册-一级类
class HealthCategorySubView1(APIView):
    def post(self, request, *args, **kwargs):
        id1 = request.data.get('id')
        print(id1)
        health_category_one_id = HealthCategory.objects.filter(id=id1).first()
        health_category_one = SubCategory.objects.filter(category_id=health_category_one_id)
        ser = HealthCategorySubSerializer(health_category_one, many=True)
        return Response(ser.data)


# 大健康和生活手册-二级类
class HealthCategorySubView2(APIView):
    def post(self, request, *args, **kwargs):
        id1 = request.data.get('id')
        print(id1)
        health_category_tow_id = SubCategory.objects.filter(id=id1).first()
        health_category_tow = HealthItem.objects.filter(sub_category_id=health_category_tow_id)
        ser = HealthItemSerializer(health_category_tow, many=True)
        return Response(ser.data)


# 医院模型
class HospitalListApiView(ListAPIView):
    queryset = Hospital.objects.all()
    serializer_class = HospitalSerializer


# 科室模型
class DepartmentListApiView(ListAPIView):
    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer


# 医生模型
class DoctorListApiView(ListAPIView):
    queryset = Doctor.objects.all()
    serializer_class = DoctorSerializer


from rest_framework.filters import OrderingFilter


# from django_filters.rest_framework import FilterSet, DjangoFilterBackend
#
#
# class DoctorListSortApiView(FilterSet):  # 继承FilterSet-作用在于过滤
#     response_count = django_filters.NumberFilter(field_name='response_count')
#     score = django_filters.NumberFilter(field_name='score')
#     price = django_filters.NumberFilter(field_name='price', lookup_expr='contains')
#
#     class Meta:
#         model = Doctor
#         fields = ['response_count', 'score', 'price']


# 根据科室查询医生
class DoctorListByDepartmentApiView(ListAPIView):
    queryset = Doctor.objects.all()
    serializer_class = DoctorSerializer
    filter_backends = [OrderingFilter]
    # filter_backends = [OrderingFilter, DjangoFilterBackend]
    ordering_fields = ['response_count', 'score', 'price']

    # filterset_class = DoctorListSortApiView

    # http: // localhost: 8000 / app / doctor_by_department /?id = 1 & score = 4.6
    def get(self, request, *args, **kwargs):
        department_id = request.query_params.get('id')
        print('----get------', department_id)
        doctors = Doctor.objects.filter(primary_department_id=department_id)
        doctors = self.filter_queryset(doctors)
        ser = DoctorSerializer(doctors, many=True)
        return Response(ser.data)

    def post(self, request):
        department_id = request.data.get('id')
        print('----------', department_id)
        doctors = Doctor.objects.filter(primary_department_id=department_id)
        ser = DoctorSerializer(doctors, many=True)
        return Response(ser.data)


# 根据科室查医院
class HospitalListByDepartmentApiView(ListAPIView):
    queryset = Hospital.objects.all()
    serializer_class = HospitalSerializer

    def get(self, request, *args, **kwargs):
        department_id = request.query_params.get('id')
        print('----get------', department_id)
        department = Department.objects.filter(id=department_id).first()
        hospitals = department.hospitals.all()
        ser = HospitalSerializer(hospitals, many=True)
        print(ser.data)
        return Response(ser.data)


# 用户咨询
class UserQuestionListApiView(ListAPIView):
    queryset = UserQuestion.objects.all()
    serializer_class = UserQuestionSerializer

    def post(self, request):
        user_id = request.data.get('id')
        print('------', user_id)
        user_data = self.get_queryset().filter(doctor_id=user_id).all()
        ser1 = UserQuestionSerializer(user_data, many=True)
        doctor_data = DoctorResponse.objects.filter(doctor_id=user_id).all()
        ser2 = DoctorResponseSerializer(doctor_data, many=True)
        user = UserModel.objects.filter(id=user_id).first()
        # user.avatar = 'http://127.0.0.1:8000/'+f'{user.avatar}'
        ser3 = UserSerializer(user, many=False)
        return Response({'user_question': ser1.data, 'doctor_response': ser2.data, "user": ser3.data})


# 医生回复
class DoctorResponseListApiView(ListAPIView):
    queryset = DoctorResponse.objects.all()
    serializer_class = DoctorResponseSerializer


# 药物模型
class MedicineListApiView(ListAPIView):
    queryset = Medicine.objects.all()
    serializer_class = MedicineSerializer


# 将医生-医院-科室-药品的多对多关系建立起来
class DoctorHospitalDepartmentMedicineView(ListAPIView):
    queryset = DoctorHospitalMedicine.objects.all()
    serializer_class = DoctorMedicineSerializer

    def post(self, request):
        doctor_all = Doctor.objects.all()
        hospital_all = Hospital.objects.all()
        medicine_all = Medicine.objects.all()
        data = request.data.get('name')
        print(data)
        if data == "推荐":
            doctor = Doctor.objects.filter(is_recommend=True)
            ser = DoctorSerializer(doctor, many=True)
            return Response({'doctor': ser.data})
        if data == "医生":
            ser = DoctorSerializer(doctor_all, many=True)
            return Response({'msg': '医生获取成功', 'doctor': ser.data})
        if data == "医院":
            ser = HospitalSerializer(hospital_all, many=True)
            return Response({'msg': '医院获取成功', 'hospital': ser.data})
        if data == "药品":
            ser = MedicineSerializer(medicine_all, many=True)
            return Response({'msg': '药品获取成功', 'medicine': ser.data})

# 视频模型
class VideosListApiView(ListAPIView):
    queryset = Video.objects.all()
    serializer_class = VideoSerializer


# 接收用户数据，创建mysql
class PatientCreateAPIView(CreateAPIView):
    queryset = Patient.objects.all()
    serializer_class = PatientSerializer
    def post(self, request, *args, **kwargs):
        datas = request.data.get('datas')
        print(datas)
        data = self.get_queryset().create(
            patientName=datas.get('patientName'),
            gender=datas.get('gender'),
            birthDate=datas.get('birthDate'),
            weight=datas.get('weight',50),
            allergyHistory=datas.get('allergyHistory'),
            pastMedicalHistory=datas.get('pastMedicalHistory'),
            liverFunction=datas.get('liverFunction'),
            kidneyFunction=datas.get('kidneyFunction'),
            pregnancyStatus=datas.get('pregnancyStatus'),
            user = datas.get('user_id')
        )
        ser = PatientSerializer(data, many=False)
        return Response({'msg': '创建成功', 'data': ser.data})
    def get(self, request, *args, **kwargs):
        data1 = self.get_queryset().all()
        ser = PatientSerializer(data1, many=True)
        return Response({'msg': '获取成功', 'data': ser.data})